/**
 * Created by jiangqifan on 16/3/28.
 */

 "use strict";

var _ = require('lodash');

class Bucket{
  constructor(maxSize){
    this.elements = [];
    this.emptys = [];
    this.indexMap = {};
    this.maxSize = maxSize || 1024;
    this._size = 0;
  }
  add(id, element){
    if(this.indexMap[id]){
      throw 'exist id:'+id;
    }
    if(this.elements.length >= this.maxSize && this.emptys.length == 0){
      throw 'bucket full';
    }
    var index = this.emptys.shift();
    if(null != index){
      this.elements[index] = element;
      this.indexMap[id] = index;
    } else {
      this.elements.push(element);
      this.indexMap[id] = this.elements.length - 1;
    }
    this._size++;
    return this;
  }
  size(){
    return this._size;
  }
  toArray(){
    return _.compact(this.elements);
  }
  remove(id){
    var index = this.indexMap[id];
    if(null == index){
      return this;
    }
    this.elements[index] = null;
    this.emptys.push(index);
    this._size--;
    delete this.indexMap[id];
  }
  get(id){
    return this.elements[this.indexMap[id]];
  }
  contains(id){
    return null != this.indexMap[id];
  }
}

module.exports = Bucket;
